var path = require('path');
var fs = require("fs");
var sql = require('mssql');

//处理Get请求，返回user.html页面
function start(response, request) {
    console.log("Request handler 'index.html' was called.");

    filePath = path.join(__dirname, './views', 'index.html');
    //读取user.html文件，然后将其写入返回结果
    fs.readFile(filePath,  'utf-8', function (err, data) {
        // 如果出现错误就抛出 err，没出错就把 html 页面返回给浏览器
        if (err) {
            throw err;
        } else {
            response.writeHead(200, {
                "Content-Type": "text/html"
            });
            
            let li_html = "";
            //连接方式："mssql://用户名:密码@ip地址:1433(默认端口号)/数据库名称"
            sql.connect("mssql://sa:sa123@DESKTOP-3BAHAU6:1433/MyDB").then(function() {
                // Query
                let queryStr = "select top 10 * from dbo.course";
                new sql.Request().query(queryStr).then(function(result) {
                    //console.log(result.recordset);
                    result.recordset.forEach(function(ele, index){
                        li_html += "<ul>";
                        li_html += "<li>" + ele.course_id + "</li>";
                        li_html += "<li class='liTitle'>" + ele.title + "</li>";
                        li_html += "<li>" + ele.dept_name + "</li>";
                        li_html += "<li>" + ele.credits + "</li>";
                        li_html += "</ul>";
                    });

                    data = data.replace('^_^', li_html);
                    response.write(data);
                    response.end();
                    
                }).catch(function(err) {
                    console.log(err);
                });
                // Stored Procedure
            }).catch(function(err) {
                console.log(err);
            })

        }
    });
}

exports.start = start;